#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/un.h>
#include <unistd.h>

#include "r_socket_domain_udp_client.h"
#include "r_socket_common.h"
#include "r_socket_obj_manager.h"

#include "utilities/string_operator.h"
#include "utilities/r_logger.h"

namespace eniac
{

r_socket_proxy_ret_t r_socket_domain_udp_client::set_socket_property(const r_socket::ptr socket_obj, r_socket_property_type type, void* property, size_t property_size)
{
    if (nullptr == socket_obj.get())
    {
        return r_socket_proxy_ret_t::NULL_PTR;
    }

    std::lock_guard<std::mutex> lg{socket_obj->m_mutex};

    if (type == r_socket_property_type::SOCKET_PROPERTY_OWN_ADDRESS)
    {
        return set_socket_own_address(socket_obj, property, property_size);
    }

    if (type == r_socket_property_type::SOCKET_PROPERTY_SERVER_ADDRESS)
    {
        return set_socket_server_address(socket_obj, property, property_size);
    }

    return r_socket_proxy_ret_t::INVALID_PROPERTY_TYPE_FOR_THE_SOCKET;
}

r_socket_proxy_ret_t r_socket_domain_udp_client::read_message(const r_socket::ptr socket_obj, r_socket_message::ptr& message)
{
    if (nullptr == socket_obj.get())
    {
        return r_socket_proxy_ret_t::NULL_PTR;
    }

    std::lock_guard<std::mutex> lg{socket_obj->m_mutex};

    if (socket_obj->m_socket_fd == INVALID_SOCKET_FD)
    {
        return r_socket_proxy_ret_t::INVALID_SOCKET_FD;
    }

    uint64_t readable_bytes = r_socket_common::get_readable_bytes_length(socket_obj->m_socket_fd);
    if (0 == readable_bytes)
    {
        return r_socket_proxy_ret_t::NO_DATA_CAN_BE_READ;
    }

    message = r_socket_message::create_obj();
    message->m_socket_id = socket_obj->m_socket_id;
    message->m_payload.resize(readable_bytes);

    ssize_t valread = read(socket_obj->m_socket_fd, message->m_payload.data(), message->m_payload.size());
    if (valread <= 0)
    {
        message.reset();
        return r_socket_proxy_ret_t::TO_READ_DATA_FROME_SOCKET_IS_FAILED;
    }

    return r_socket_proxy_ret_t::OK; 
}

r_socket_proxy_ret_t r_socket_domain_udp_client::send_message(const r_socket::ptr socket_obj, const std::vector<uint8_t>& message)
{
    if (nullptr == socket_obj.get())
    {
        return r_socket_proxy_ret_t::NULL_PTR;
    }

    std::lock_guard<std::mutex> lg{socket_obj->m_mutex};

    if (socket_obj->m_socket_fd == INVALID_SOCKET_FD)
    {
        return r_socket_proxy_ret_t::INVALID_SOCKET_FD;
    }

    struct sockaddr_un server_addr;
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sun_family = AF_UNIX;
    strncpy(&server_addr.sun_path[1], socket_obj->m_server_address.data(), sizeof(server_addr.sun_path) - 2);

    LOG_DBG() << "Server Address is " << socket_obj->m_server_address;

    ssize_t send_len = sendto(
        socket_obj->m_socket_fd,
        message.data(),
        message.size(),
        0,
        (struct sockaddr*)&server_addr,
        sizeof(server_addr)
    );
    if (send_len != message.size())
    {
        //TODO Make Sure ALL Data is sent
        return r_socket_proxy_ret_t::TO_SEND_DATA_IS_FAILED;
    }

    LOG_DBG() << "To send Message is success";
    return r_socket_proxy_ret_t::OK;
}

r_socket_proxy_ret_t r_socket_domain_udp_client::start_socket(const r_socket::ptr socket_obj)
{
    if (nullptr == socket_obj.get())
    {
        return r_socket_proxy_ret_t::NULL_PTR;
    }

    std::lock_guard<std::mutex> lg{socket_obj->m_mutex};

    if (socket_obj->m_own_address.empty())
    {
        return r_socket_proxy_ret_t::OWN_ADDRESS_HAS_NOT_BEEN_SET_YET;
    }

    if (socket_obj->m_server_address.empty())
    {
        return r_socket_proxy_ret_t::SERVER_ADDRESS_HAS_NOT_BEEN_SET_YET;
    }

    if (socket_obj->m_socket_fd != INVALID_SOCKET_FD)
    {
        return r_socket_proxy_ret_t::SOCKET_FD_HAS_BEEN_SET;
    }

    if ((socket_obj->m_socket_fd = socket(AF_UNIX, SOCK_DGRAM, 0)) == -1)
    {
        return r_socket_proxy_ret_t::TO_CREATE_SOCKET_FD_IS_FAILED;
    }

    sockaddr_un self_addr;
    memset(&self_addr, 0, sizeof(self_addr));
    self_addr.sun_family = AF_UNIX;
    strncpy(&self_addr.sun_path[1], socket_obj->m_own_address.data(), socket_obj->m_own_address.length());
    int bind_ret = bind(socket_obj->m_socket_fd, (struct sockaddr*)&self_addr, sizeof(self_addr));
    if (bind_ret < 0)
    {
        LOG_DBG() << "Bind Ret is " << bind_ret << " errno " <<  errno <<  "  strerror(errno) " << strerror(errno);
        close(socket_obj->m_socket_fd);
        socket_obj->m_socket_fd = INVALID_SOCKET_FD;
        return r_socket_proxy_ret_t::TO_BIND_ADDRESS_TO_FD_IS_FAILED;
    }

    socket_obj->m_status = r_socket_status_t::R_SOCKET_STATUS_STARTED;
    r_socket_obj_manager::get_instance()->update_socket_obj(socket_obj);
    return r_socket_proxy_ret_t::OK;
}

void r_socket_domain_udp_client::close_socket(const r_socket::ptr socket_obj)
{
    if (nullptr == socket_obj.get())
    {
        return;
    }

    std::lock_guard<std::mutex> lg{socket_obj->m_mutex};

    if (socket_obj->m_socket_fd == INVALID_SOCKET_FD)
    {
        return;
    }

    close(socket_obj->m_socket_fd);
    socket_obj->m_socket_fd = INVALID_SOCKET_FD;
    socket_obj->m_status = r_socket_status_t::R_SOCKET_STATUS_STOPPING;
    r_socket_obj_manager::get_instance()->update_socket_obj(socket_obj);
}


r_socket_proxy_ret_t r_socket_domain_udp_client::set_socket_own_address(const r_socket::ptr socket, void* property, size_t property_size)
{
    LOG_DBG() << "r_socket_domain_udp_client::set_socket_own_address entry";

    if ( 0 >= property_size  ||
         property_size > 107 )
    {
        return r_socket_proxy_ret_t::INVALID_PROPERTY_LENGTH;
    }

    const char* c_addr = reinterpret_cast<const char*>(property);
    if (strlen(c_addr) != property_size)
    {
        return r_socket_proxy_ret_t::INVALID_PROPERTY_VALUE;
    }

    socket->m_own_address = c_addr;

    return r_socket_proxy_ret_t::OK;
}

r_socket_proxy_ret_t r_socket_domain_udp_client::set_socket_server_address(const r_socket::ptr socket, void* property, size_t property_size)
{
    LOG_DBG() << "r_socket_domain_udp_client::set_socket_server_address entry";

    if ( 0 >= property_size  ||
         property_size > 107 )
    {
        return r_socket_proxy_ret_t::INVALID_PROPERTY_LENGTH;
    }

    const char* c_addr = reinterpret_cast<const char*>(property);
    if (strlen(c_addr) != property_size)
    {
        return r_socket_proxy_ret_t::INVALID_PROPERTY_VALUE;
    }

    socket->m_server_address = c_addr;

    return r_socket_proxy_ret_t::OK;
}

}